package thread;
//模拟实现定时器

import java.util.PriorityQueue;


//描述任务
class MyTimerTask implements Comparable<MyTimerTask>{
    private Runnable task;
    private long time;

    public MyTimerTask(Runnable task, long time){
        this.task = task;
        this.time = time;
    }

    @Override
    public int compareTo(MyTimerTask o) {
        return  (int)(this.time - o.time);
    }

    public long getTime(){
        return this.time;
    }

    public void run(){
        task.run();
    }
}


class MyTimer{
    private PriorityQueue<MyTimerTask> queue = new PriorityQueue<>();//小根堆存储任务，以时间比较
    Object locker = new Object();

    public MyTimer(){
        Thread t = new Thread(()->{
            while(true){
                try{
                    synchronized (locker){
                        while(queue.isEmpty()){//解决忙等
                            locker.wait();
                        }
                        MyTimerTask task = queue.peek();
                        if(task.getTime() > System.currentTimeMillis() ){
                            locker.wait(task.getTime() - System.currentTimeMillis());
                        }else{
                            task.run();
                            queue.poll();
                        }

                    }
                }catch(InterruptedException e){
                    e.printStackTrace();
                }
            }
        });
        t.start();
    }

    public void schedule(Runnable task,long delay){
        synchronized (locker){
            MyTimerTask myTimerTask = new MyTimerTask(task,delay+System.currentTimeMillis());
            queue.offer(myTimerTask);
            locker.notify();//添加任务时唤醒
        }

    }

}


public class Demo21 {
    public static void main(String[] args) {
        MyTimer timer = new MyTimer();
        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello 3000");
            }
        },3000);

        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello 2000");
            }
        },2000);

        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello 1000");
            }
        },1000);
    }
}
